<?php

namespace App\Libs;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class RefreshTokenLibrary
{

    const key = 'slsqncudWdOws!#bbsadfaklj';
    const accessTokenTTL="";

    /**
     * 生成token
     */
    public static function createAccessToken($data, $overdue_time=7200, $prefix = 'token_front_')
    {
        if($prefix=='token_backend_'){
            $type='1';
        }else{
            $type='2';
        }
      //  $data['type']=$type;
        $time = time();
        $payload = [
            //"iss" => "",
            //"aud" => "",
            "iat" => $time,
            "nbf" => $time,
            "exp" => $time+$overdue_time,
            "data" => $data
        ];
        $token = JWT::encode($payload, self::key, 'HS256');
        //cache()->set($prefix.$data['user_id'].'_'.$time, $token, $overdue_time);
        return 'bearer '.$token;
    }
 
    /**
     * 验证token
     */
    public static function validateToken($token)
    {
        if(!$token){
            return false;
        }
        if (strpos($token,'bearer') !== false) {
            $token = trim(ltrim($token,'bearer'));
        }
       // dd($token);exit;
        try {
            //JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            #解码 JWT 并验证签名
            $decoded = JWT::decode($token, new Key(self::key, 'HS256'));
            #检查是否过期
            if (isset($decoded->exp)) {
                $expirationTime = $decoded->exp; // 获取过期时间戳
                $currentTime = time(); // 当前时间的时间戳
                if ($currentTime > $expirationTime) {
                    #令牌已过期
                    return false;
                } else {
                    #令牌有效且未过期
                    return $decoded;
                }
            } else {
                #令牌没有过期时间
                return false;
            }
            
        }catch (\Exception $e){
            $msg='Token validation failed: '.$e->getMessage();
            return false;
        }

    }
    public static function validateToken3($token)
    {
        //JWT::$leeway = 60;//当前时间减去60，把时间留点余地
        return JWT::decode($token, new Key(self::key, 'HS256'));
    }

    #当access_token过期，使用refresh_token刷新
    public  function refreshToken($refreshToken) {
        // 假设你已经有了用于签名的密钥
        $key = "your_secret_key";
        // 定义token的有效期，例如1小时（3600秒）
        $accessTokenTTL = 3600;
        $refreshTokenTTL = 604800; // 7 days

        try {
            $decoded = $this->validateToken($refreshToken);
            $issuedAt = time();
     
            $newAccessToken = [
                'iat' => $issuedAt,
                'exp' => $issuedAt + $accessTokenTTL,
                'data' => [
                    'userID' => $decoded->data->userID
                ]
            ];
            $newAccessToken = JWT::encode($newAccessToken, $key);
     
            return $newAccessToken;
        } catch (\Exception $e) {
            // 无效的refresh_token
            return null;
        }
    }
   




}
